
import requests
from config.cfg import *
from pprint import pprint


class Student:

    def _printResponse(self, response):
        print('\n\n-------- HTTP response * begin -------')
        print(response.status_code)

        for k, v in response.headers.items():
            print(f'{k}: {v}')

        print('')

        body = response.content.decode('utf8')
        print(body)

        try:
            jsonBody = response.json()
            print(f'\n\n---- 消息体json ----\n')
            pprint(jsonBody)
        except:
            print('消息体不是json格式！！')

        print('-------- HTTP response * end -------\n\n')

    # 列出学生
    def list_student(self):
        params = {
            "vcode": g_code,
            "action": "search_with_pagenation",
        }

        res = requests.get(url=g_api_url_student, params=params)

        self._printResponse(res)

        return res

    # 添加学生
    def add_student(self, username, realname, gradeid,
                    classid, phonenumber):
        data = {
            "vcode": g_code,
            "action": "add",
            "username": username,
            "realname": realname,
            "gradeid": gradeid,
            "classid": classid,
            "phonenumber": phonenumber,
        }

        res = requests.post(url=g_api_url_student, data=data)

        self._printResponse(res)

        return res

    # 修改学生
    def modify_student(self, studentid, realname=None, phonenumber=None):
        url = f"{g_api_url_student}/{studentid}"
        data = {
            "vcode": g_code,
            "action": "modify"
        }

        if realname:
            data['realname'] = realname
        if phonenumber:
            data['phonenumber'] = phonenumber

        res = requests.put(url=url, data=data)

        self._printResponse(res)

        return res

    # 删除学生
    def delete_student(self, studentid):
        url = f'{g_api_url_student}/{studentid}'
        data = {
            "vcode": g_code
        }

        res = requests.delete(url=url, data=data)

        self._printResponse(res)

        return res

    # 删除所有学生
    def delete_all_student(self):
        ret = self.list_student()
        retList = ret.json()
        for one in retList['retlist']:
            self.delete_student(studentid=one['id'])


sm = Student()
